package com.ruoyi.basic.controller;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.ruoyi.api.system.utils.ShiroUtils;
import com.ruoyi.api.system.utils.poi.ExcelUtil;
import com.ruoyi.basic.constant.BasicConstants;
import com.ruoyi.basic.domain.BasicDuty;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.domain.BasicWork;
import com.ruoyi.basic.service.IBasicUserService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.basic.domain.BasicEducate;
import com.ruoyi.basic.service.IBasicEducateService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * 教育经历Controller
 * 
 * @author ruoyi
 * @date 2021-08-22
 */
@Controller
@RequestMapping("/basic/educate")
public class BasicEducateController extends BaseController
{
    private String prefix = "basic/educate";

    @Autowired
    private IBasicEducateService basicEducateService;

    @Autowired
    private IBasicUserService basicUserService;

    @RequiresPermissions("basic:educate:view")
    @GetMapping()
    public String educate(ModelMap mmap)
    {
        if(ShiroUtils.getSysUser().isAdmin() || ShiroUtils.getSubject().hasRole("administrator") || ShiroUtils.getSubject().hasRole("Science and education")){
            mmap.put("showFlag", true);
        }else{
            mmap.put("showFlag", false);
        }
        return prefix + "/educate";
    }

    /**
     * 查询教育经历列表
     */
    @RequiresPermissions("basic:educate:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BasicEducate basicEducate)
    {
        startPage();
        if(!ShiroUtils.getSysUser().isAdmin() && !ShiroUtils.getSubject().hasRole("administrator") && !ShiroUtils.getSubject().hasRole("Science and education")){
            basicEducate.setIdCard(ShiroUtils.getLoginName());
        }
        List<BasicEducate> list = basicEducateService.selectBasicEducateList(basicEducate);
        return getDataTable(list);
    }

    /**
     * 导出员工教育经历
     */
    @RequiresPermissions("basic:educate:export")
    @Log(title = "员工教育经历", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BasicEducate basicEducate)
    {
        List<BasicEducate> list = basicEducateService.selectBasicEducateList(basicEducate);
        ExcelUtil<BasicEducate> util = new ExcelUtil<BasicEducate>(BasicEducate.class);
        return util.exportExcel(list, "员工教育经历信息数据");
    }

    @Log(title = "员工教育经历", businessType = BusinessType.IMPORT)
    @RequiresPermissions("basic:educate:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<BasicEducate> util = new ExcelUtil<BasicEducate>(BasicEducate.class);
        List<BasicEducate> educateList = util.importExcel(file.getInputStream());
        String message = basicEducateService.importEducate(educateList, updateSupport, ShiroUtils.getLoginName());
        return AjaxResult.success(message);
    }

    @RequiresPermissions("basic:educate:import")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<BasicEducate> util = new ExcelUtil<BasicEducate>(BasicEducate.class);
        return util.importTemplateExcel("员工教育经历信息");
    }

    /**
     * 新增教育经历
     */
    @GetMapping("/add/{userId}")
    public String add(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        BasicUser user = basicUserService.selectBasicUserById(userId);
        mmap.put("user", user == null ? new BasicUser() : user);
        return prefix + "/add";
    }

    /**
     * 新增保存教育经历
     */
    @RequiresPermissions("basic:educate:add")
    @Log(title = "教育经历", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam(required = false) MultipartFile file, BasicEducate basicEducate) throws IOException {
        if(!file.isEmpty()) {
            BasicUser basicUser = basicUserService.selectBasicUserById(basicEducate.getUserId());
            String fileUrl = FileUploadUtils.upload(RuoYiConfig.getUploadPath() + "/educate/" + basicUser.getIdCard(), file, false);
            basicEducate.setFileUrl(fileUrl);
        }
        if(BasicConstants.EDUCATE_NO_NOT_UNIQUE.equals(basicEducateService.checkUserEducateUnique(basicEducate))){
            return error("新增教育经历失败，教育经历已存在");
        }
        basicEducate.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(basicEducateService.insertBasicEducate(basicEducate));
    }

    /**
     * 修改教育经历
     */
    @GetMapping("/edit/{educateId}")
    public String edit(@PathVariable("educateId") Long educateId, ModelMap mmap)
    {
        BasicEducate basicEducate = basicEducateService.selectBasicEducateByEducateId(educateId);
        mmap.put("basicEducate", basicEducate);
        return prefix + "/edit";
    }

    /**
     * 修改保存教育经历
     */
    @RequiresPermissions("basic:educate:edit")
    @Log(title = "教育经历", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestParam(required = false) MultipartFile file, BasicEducate basicEducate) throws IOException {
        if(!file.isEmpty()) {
            BasicEducate old = basicEducateService.selectBasicEducateByEducateId(basicEducate.getEducateId());
            FileUtils.deleteFile(RuoYiConfig.getProfile() + StringUtils.substringAfter(old.getFileUrl(), Constants.RESOURCE_PREFIX));

            BasicUser basicUser = basicUserService.selectBasicUserById(basicEducate.getUserId());
            String fileUrl = FileUploadUtils.upload(RuoYiConfig.getUploadPath() + "/educate/" + basicUser.getIdCard(), file, false);
            basicEducate.setFileUrl(fileUrl);
        }
        if(BasicConstants.EDUCATE_NO_NOT_UNIQUE.equals(basicEducateService.checkUserEducateUnique(basicEducate))){
            return error("修改教育经历失败，教育经历已存在");
        }
        basicEducate.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(basicEducateService.updateBasicEducate(basicEducate));
    }

    /**
     * 删除教育经历
     */
    @RequiresPermissions("basic:educate:remove")
    @Log(title = "教育经历", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(basicEducateService.deleteBasicEducateByEducateIds(ids));
    }

    /**
     * 校验证书编号
     */
    @PostMapping("/checkUserEducateUnique")
    @ResponseBody
    public String checkUserEducateUnique(BasicEducate basicEducate)
    {
        return basicEducateService.checkUserEducateUnique(basicEducate);
    }

    /**
     * 导出教育经历
     * @param educateIds
     * @param response
     * @throws Exception
     */
    @RequiresPermissions("basic:educate:download")
    @Log(title = "教育经历", businessType = BusinessType.EXPORT)
    @GetMapping( "/download")
    public void download(String educateIds, HttpServletResponse response) throws Exception
    {
        List<BasicEducate> fileList = basicEducateService.selectBasicEducateByEducateIds(educateIds);
        String strZipPath = RuoYiConfig.getDownloadPath() + System.currentTimeMillis() + ".zip";
        ZipOutputStream out = null;
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try{
            out = new ZipOutputStream(new FileOutputStream(strZipPath));
            ServletOutputStream outputStream = response.getOutputStream();
            for(BasicEducate basicEducate : fileList) {
                String downloadPath = RuoYiConfig.getProfile() + StringUtils.substringAfter(basicEducate.getFileUrl(), Constants.RESOURCE_PREFIX);
                // 下载名称
                String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
                out.putNextEntry(new ZipEntry(downloadName));
                fis = new FileInputStream(new File(downloadPath));
                byte[] b = new byte[1024];
                int length;
                while ((length = fis.read(b)) > 0)
                {
                    out.write(b, 0, length);
                }
                out.closeEntry();
            }
            out.close();
            bis = new BufferedInputStream(new FileInputStream(strZipPath));
            FileCopyUtils.copy(bis, outputStream);
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            IOUtils.close(bis);
            IOUtils.close(fis);
            IOUtils.close(out);
        }
        FileUtils.deleteFile(strZipPath);
    }
}
